package org.one.afternoon.controller;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.Data;
import org.apache.ibatis.annotations.Param;
import org.one.afternoon.common.Result;
import org.one.afternoon.common.SimpleUtils;
import org.one.afternoon.domain.*;
import org.one.afternoon.forest.FrontendClient;
import org.one.afternoon.quartz.QuartzBean;
import org.one.afternoon.quartz.QuartzUtils;
import org.one.afternoon.service.JobService;
import org.one.afternoon.service.TriggerService;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/quartz")
public class QuartzController {
    //注入任务调度
    @Autowired
    private Scheduler scheduler;

    @Autowired
    private TriggerService triggerService;

    @Autowired
    private JobService jobService;

    @Autowired
    private FrontendClient frontendClient;

    @CrossOrigin // 跨域访问
    @GetMapping("/all")
    @ResponseBody
    public Result<List<JobAndTrigger>> findAll() throws ParseException {
        List<JobAndTrigger> resultList=new ArrayList<>();
        List<TriggerDetails> triggerList = triggerService.list(null);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (TriggerDetails td: triggerList) {
            String time = sdf.format(Long.parseLong(td.getPrevFireTime()));
            td.setPrevFireTime(time);
            String time2 = sdf.format(Long.parseLong(td.getNextFireTime()));
            td.setNextFireTime(time2);
        }
        List<JobDetails> jobList = jobService.list(null);
        for(int i=0;i<jobList.size();i++){
            JobAndTrigger jobAndTrigger = new JobAndTrigger();
            jobAndTrigger.setJobName(jobList.get(i).getJobName());
            jobAndTrigger.setDescription(jobList.get(i).getDescription());
            jobAndTrigger.setNextFireTime(triggerList.get(i).getNextFireTime());
            jobAndTrigger.setPrevFireTime(triggerList.get(i).getPrevFireTime());
            jobAndTrigger.setTriggerState(triggerList.get(i).getTriggerState());
            resultList.add(jobAndTrigger);
        }
        return Result.success(resultList);
    }

    @CrossOrigin
    @PostMapping("/queryOne")
    @ResponseBody
    public Result<List<JobAndTrigger>> queryOne(@RequestParam String str) {

        LambdaQueryWrapper<JobDetails> jobDetailsLambdaQueryWrapper=new LambdaQueryWrapper<>();
        jobDetailsLambdaQueryWrapper.like(StringUtils.isNotBlank(str),JobDetails::getJobName,str);
        List<JobDetails> jobs = jobService.list(jobDetailsLambdaQueryWrapper);

        LambdaQueryWrapper<TriggerDetails> triggerDetailsLambdaQueryWrapper=new LambdaQueryWrapper<>();
        triggerDetailsLambdaQueryWrapper.like(StringUtils.isNotBlank(str),TriggerDetails::getJobName,str);
        List<TriggerDetails> triggers = triggerService.list(triggerDetailsLambdaQueryWrapper);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (TriggerDetails td: triggers) {
            String time = sdf.format(Long.parseLong(td.getPrevFireTime()));
            td.setPrevFireTime(time);
            String time2 = sdf.format(Long.parseLong(td.getNextFireTime()));
            td.setNextFireTime(time2);
        }

        List<JobAndTrigger> list=new ArrayList<>();
        for(int i=0;i<jobs.size();i++){
            JobAndTrigger jobAndTrigger=new JobAndTrigger();
            jobAndTrigger.setTriggerState(triggers.get(i).getTriggerState());
            jobAndTrigger.setDescription(triggers.get(i).getDescription());
            jobAndTrigger.setJobName(triggers.get(i).getJobName());
            jobAndTrigger.setPrevFireTime(triggers.get(i).getPrevFireTime());
            jobAndTrigger.setNextFireTime(triggers.get(i).getNextFireTime());
            list.add(jobAndTrigger);
        }
        return Result.success(list);
    }

    @CrossOrigin
    @PostMapping("/create")
    @ResponseBody
    public Result<String> createJob(@RequestBody QuartzBean quartzBean) {
        long count = jobService.count();
        count++;
        quartzBean.setId(String.valueOf(count));
        try{
            QuartzUtils.createScheduleJob(scheduler,quartzBean);
            return Result.success("新建任务成功");
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    @CrossOrigin
    @PostMapping("/remove")
    @ResponseBody
    public Result<String> removeJob(@RequestParam String jobName) {
        try{
            QuartzUtils.deleteScheduleJob(scheduler,jobName);
            return Result.success("移除任务成功");
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    @CrossOrigin
    @PostMapping("/pause")
    @ResponseBody
    public Result<String> pauseJob(@RequestParam String jobName) {
        try{
            QuartzUtils.pauseScheduleJob(scheduler,jobName);
            return Result.success("暂停任务成功");
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    @CrossOrigin
    @PostMapping("/resume")
    @ResponseBody
    public Result<String> resumeJob(@RequestParam String jobName) {
        try{
            QuartzUtils.resumeScheduleJob(scheduler,jobName);
            return Result.success("恢复任务成功");
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    @CrossOrigin
    @PostMapping("/update")
    @ResponseBody
    public Result<String> updateJob(@RequestBody QuartzBean quartzBean) {
        try{
            QuartzUtils.updateScheduleJob(scheduler,quartzBean);
            return Result.success("修改任务成功");
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    @Data
    private class JobAndTrigger {
        private String JobName;
        private String Description;
        private String triggerState;
        private String prevFireTime;
        private String nextFireTime;
    }
}
